package com.mky.mkcompany.tool;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * Created by Administrator on 2016/12/28.
 */
public class FileDownloadUtil {
    private final static org.apache.log4j.Logger LOGGER = org.apache.log4j.Logger.getLogger(FileDownloadUtil.class);

    public  static void fileDownload(HttpServletRequest request, HttpServletResponse response,
                               File file, String fileName){
        OutputStream out = null;
        BufferedInputStream bis = null;
        byte[] buff = new byte[1024];
        try {
            response.reset();
            out = response.getOutputStream();
            String agent=request.getHeader("User-Agent").toLowerCase();
            agent = EgineUtil.getBrowserName(agent);
            if (agent.contains("ie") || agent.contains("webkit")) {
                response.setHeader("Content-Disposition", "attachment; filename=\"" + new String(URLEncoder.encode(fileName, "UTF-8"))+ "\"");  //设置下载文件名
            }else{
                response.setHeader("Content-Disposition", "attachment; filename=\"" + new String(fileName.getBytes(),"ISO8859-1")+ "\"");  //设置下载文件名
            }
            response.setContentType("application/octet-stream" + "; charset=UTF-8");  //设置二进制文件下载
            bis = new BufferedInputStream(new FileInputStream(file));
            int i = bis.read(buff);
            while (i != -1) {
                out.write(buff, 0, buff.length);
                out.flush();
                i = bis.read(buff);
           }
            //out.flush();
            response.flushBuffer();
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }finally {
            try {
                out.close();
            } catch (IOException e) {
                LOGGER.error(e.getMessage(), e);
            }
        }
    }

}
